package com.github.bobjoy.java.io;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileDemo {

    @Test
    public void readByte() throws IOException {
        FileInputStream fis = new FileInputStream("E:\\workspaces\\study\\tech-road\\网址收藏.md");

        int size = fis.available();
        for (int i=0; i<size; i++) {
            System.out.println((char) fis.read());
        }
    }

    @Test
    public void readString() throws IOException {

        Reader reader = new FileReader("E:\\workspaces\\study\\tech-road\\网址收藏.md");

        int ch;
        while ((ch = reader.read()) != -1) {
            System.out.print((char)ch);
        }

    }

    @Test
    public void readLine() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("E:\\workspaces\\study\\tech-road\\网址收藏.md"));

        int num = 1;
        List<String> list = new LinkedList<>();
        while (reader.read() != -1) {
            String line = reader.readLine();
            String url = getURL(line);

            if (url != null) {

                line = line.replace(url, url + "?_blank");

                if (list.contains(url)) {
                    System.out.println((list.indexOf(url)+1) + ":" + num);
                }

                String domain = getDomain(url);
                System.out.println(domain);
            }

            list.add(url);
            num++;
        }
    }

    private String getURL(String line) {

        Pattern compile = Pattern.compile("(https?://.+?)\\)?$");
        Matcher matcher = compile.matcher(line);
        if (matcher.find()) {
            return matcher.group(1);
        }

        return null;

    }

    private String getDomain(String url) {

        Pattern compile = Pattern.compile("(https?://.+?)/");
        Matcher matcher = compile.matcher(url);
        if (matcher.find()) {
            return matcher.group(1);
        }

        return null;

    }

}
